package com.oncliedisk.administrator.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.oncliedisk.administrator.Base.BaseTaskFragment;
import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.adapter.TaskAdapter;
import com.oncliedisk.administrator.content.OnlineConfig;
import com.oncliedisk.administrator.interfaces.OnActionClickListener;
import com.oncliedisk.administrator.interfaces.onDownFileListener;
import com.oncliedisk.administrator.model.FileTaskModel;
import com.oncliedisk.administrator.service.TransmissionService;
import com.oncliedisk.administrator.service.UploadService;
import com.oncliedisk.administrator.utils.FileUtils;
import com.oncliedisk.administrator.utils.LargeFileUpload;
import com.oncliedisk.administrator.utils.OnlineUtils;
import com.vdisk.net.VDiskAPI;
import com.ypy.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2015/12/17.
 */
public class FragUp extends BaseTaskFragment implements OnActionClickListener, onDownFileListener {

    private Intent intent;
    private UploadService mService;
    private Activity activity;
    private ServiceConection conection;

    public FragUp(Activity activity) {
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();
        conection = new ServiceConection();
        intent = new Intent(activity, UploadService.class);
        activity.bindService(intent, conection, getActivity().BIND_AUTO_CREATE);
        mAdapter = new TaskAdapter(getActivity(), Dao.getInstance(getActivity()).getTaskFileByType("taskType=?", new String[]{OnlineConfig.TYPE_UP}), this);
        listview.setAdapter(mAdapter);
    }

    public void onEventMainThread(String type) {
        if (type.equals(OnlineConfig.TYPE_UP)) {
            referData();
        }
    }

    /**
     * 刷新获取下载页面的所有未下载的项目进行下载
     */
    private void referData() {
        if (mAdapter != null) {
            Log.i("info", "接收到消息");
            List<FileTaskModel> taskFileByType = Dao.getInstance(getActivity()).getTaskFileByType("taskType=? and state=?", new String[]{OnlineConfig.TYPE_UP, String.valueOf(FileTaskModel.STATE_WAIT_DOWN)});
            for (FileTaskModel model : taskFileByType) {
                Dao.getInstance(getActivity()).updateState(FileTaskModel.STATE_DOWNING, null, model);
                model.setState(FileTaskModel.STATE_DOWNING);
            }
            mAdapter.getData().addAll(taskFileByType);
            mAdapter.notifyDataSetChanged();
            for (FileTaskModel model1 : taskFileByType) {
                Log.i("info", "开始添加线程");
                mService.addFileModel(getActivity(), model1, OnlineUtils.getMapi(getActivity()), this);
                mService.downFile();
            }
        }
    }

    @Override
    public void onDownFinish(FileTaskModel model, VDiskAPI.Entry metadata) {
        //下载完成，更改对象状态，更新数据库，更新适配器
        for (FileTaskModel molder : mAdapter.getData()) {
            if (molder.getId() == model.getId()) {
                molder.setState(FileTaskModel.STATE_DOWN_SUCCESS);
                Dao.getInstance(getActivity()).updateState(FileTaskModel.STATE_DOWN_SUCCESS, FileUtils.getNowTime(), molder);
                if (model.getTaskType().equals(OnlineConfig.TYPE_UP)) {
                    List<VDiskAPI.Entry> list = new ArrayList<VDiskAPI.Entry>();
                    list.add(metadata);
                    Dao.getInstance(getActivity()).saveFile(null, list, OnlineUtils.getMapi(getActivity()));
                }
            }
        }
        mAdapter.notifyDataSetChanged();
        mService.isDowning = false;
        mService.downFileByFinish(model, getActivity(), OnlineUtils.getMapi(getActivity()), this);
        mAdapter.getData();
        EventBus.getDefault().post(new String(OnlineConfig.TYPE_UP_SUCCESS));
    }

    @Override
    public void onDownFail(String errorInfo) {
    }

    @Override
    public void onProgress(int percent, String currSize, FileTaskModel model) {
        //根据需要更新对象的ID，更新数据
        Log.i("info", model.getFileName() + "下载进度" + percent);
        for (FileTaskModel molder : mAdapter.getData()) {
            if (molder.getId() == model.getId()) {
                molder.setProgress(String.valueOf(percent));
                molder.setCurrSize(currSize);
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("progress", String.valueOf(percent));
                map.put("currSize", currSize);
                Dao.getInstance(getActivity()).updateData(molder.getId(), map);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActionClick(FileTaskModel model, int type) {
        mAdapter.getData();
        if (type == 1) {
            //需要停止操作
            mService.downAction(model, TransmissionService.THEAD_CLOSE, getActivity(), OnlineUtils.getMapi(getActivity()), this, null);
        } else if (type == 2) {
            //需要继续上传下载操作
            Toast.makeText(getActivity(), "继续上传", Toast.LENGTH_SHORT).show();
            LargeFileUpload file = new LargeFileUpload(getActivity(), model, OnlineUtils.getMapi(getActivity()), this);
            mService.downAction(model, TransmissionService.THREAD_EXCEL, getActivity(), OnlineUtils.getMapi(getActivity()), this, file);
            file.execute();
        }

    }

    public class ServiceConection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("info", "服务绑定成功");
            UploadService.MyBinder iBinder = (UploadService.MyBinder) service;
            mService = iBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(getActivity(), "服务获取失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("info", "解除绑定");
        getActivity().unbindService(conection);
        for (FileTaskModel model : mAdapter.getData()) {
            if (model.getState() == FileTaskModel.STATE_DOWNING) {
                //停止他的线程并且改变他的状态
                Dao.getInstance(getActivity()).updateState(FileTaskModel.STATE_DOWN_STOP, null, model);
                mService.downAction(model, TransmissionService.THEAD_CLOSE, getActivity(), OnlineUtils.getMapi(getActivity()), this, null);
            }
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        //长按事件
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("删除操作");
        builder.setMessage("你真的要删除此记录吗");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                FileTaskModel model = (FileTaskModel) mAdapter.getItem(position);
                Dao.getInstance(getActivity()).deleteTask(model);
                mService.downAction(model, TransmissionService.THEAD_CLOSE, getActivity(), OnlineUtils.getMapi(getActivity()), null, null);
                mAdapter.getData().remove(model);
                mAdapter.notifyDataSetChanged();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        return false;
    }
}
